package com.example.mq.common;

import java.io.*;

/**
 * 序列化 反序列化
 */
public class BinaryTool {
    //将一个对象序列化成一个字节数组
    //使用到
    public static byte[]  toBytes(Object object) throws IOException {
        //将object对象写入到  ByteArrayOutputStream 中统一为byte[]
        try(ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream()){
            try(ObjectOutputStream objectOutputStream = new ObjectOutputStream(byteArrayOutputStream)){
                //writeObject会将对象转为二进制数据 写入到objectOutputStream中
                // objectOutputStream有关联到了 byteArrayOutputStream 座椅最终数据会写入到byteArrayOutputStream
                objectOutputStream.writeObject(object);
            }
            return byteArrayOutputStream.toByteArray();
        }
    }
    //将一个字节数组反序列化成一个对象
    public static  Object fromBytes(byte[] data) throws IOException, ClassNotFoundException {
        Object object = null;
        try(ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(data)){
            try(ObjectInputStream objectInputStream = new ObjectInputStream(byteArrayInputStream)){
                object = objectInputStream.readObject();
            }
            //返回对象
            return object;
        }
    }
}
